<template>
	<view class="edit_phone">
		<view class="form_box">
			<u-field label-width='0' v-model="form.telPhone" label="" placeholder="请填写手机号">
			</u-field>

			<view class="">
				<u-field v-model="form.code" label-width='0' placeholder="请填写验证码">
					<u-button size="mini" slot="right" type="primary" @click="getCode">{{codeText}}</u-button>
				</u-field>
				<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
			</view>
		</view>
		<u-button type='primary' shape="circle" @click="submit">
			{{isLogin==0?'立即修改':'确定'}}
		</u-button>
	</view>
</template>

<script>
	import cacheFunc from '@/utils/cache.js'
	export default {
		data() {
			return {
				codeText: '',
				isLogin: 0,
				form: {
					telPhone: '',
					code: '',
				}
			};
		},
		onReady() {
			// this.$refs.uForm.setRules(this.rules);
		},
		onLoad(e) {
			if (e && e.isLogin) {
				this.isLogin = e.isLogin
			}
		},
		methods: {
			async submit() {
				if (!this.form.telPhone) {
					this.$u.toast('请先输入手机号码!');
					return
				}

				if (!this.form.code) {
					this.$u.toast('请先输入验证码!');
					return
				}

				if (this.isLogin == 1) {
					uni.navigateTo({
						url: '/pages/editPassword/editPassword?telPhoneForm=' + JSON.stringify(this.form)
					})
				} else {
					const res = await this.$u.api.replaceTelPhone({
						telPhone: this.form.telPhone,
						code: this.form.code
					})
					this.cache.removeCache('token')
					this.cache.removeCache('user')
					uni.showToast({
						title: '更换成功,请从新登陆',
						icon: 'none'
					})
					// code-10400 用户未登录
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						})
					}, 1000)
				}

			},
			codeChange(text) {
				this.codeText = text;
			},
			async getCode() {
				if (!this.form.telPhone) {
					this.$u.toast('请先输入手机号码!');
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					const res = await this.$u.api.sendSMS(this.form)
					console.log(res, '验证码')
					uni.hideLoading();
					// 通知验证码组件内部开始倒计时
					this.$refs.uCode.start();
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit_phone {
		padding: 0 30rpx;

		.form_box {
			margin-bottom: 100rpx;
		}
	}
</style>
